package NetWork;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 故我
 * Date: 2023-10-19
 * Time: 22:29
 */

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIP =null;
    private int serverPort =0;

    //客户端要指定服务器的IP和端口号进行发送数据
    public UdpEchoClient(String serverIP, int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverIP = serverIP;
        this.serverPort = serverPort;
    }

    public void Start() throws IOException {
        System.out.println("客户端启动!");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.print("> ");
            String request = scanner.next();
            if(request.equals("exit")){
                System.out.println("byebye");
                break;
            }
            //将这个String类型数据构建成DatagramPacket数据报  并填入地址信息使用InetAddress.getByName
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIP), serverPort);
            socket.send(requestPacket);
            //等待服务器接收数据后进行处理，并返回回来
            DatagramPacket recvPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(recvPacket);
            //将这个数据报进行处理，等到里面的数据
            String recvStr = new String(recvPacket.getData(),0,recvPacket.getLength());
            System.out.println(recvStr);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.Start();
    }
}


